﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using handvn.Models;
using System.IO;

namespace handvn.Controllers
{
    public class AccountController : Controller
    {
        private HandvnContext db = new HandvnContext();
        public ActionResult Admin()
        {
            Session.Clear();
            return View();
        }

        //
        // POST: /Account/Login

        [HttpPost]
        public ActionResult Admin(AccountSystem model)
        {
            UserDAO usDAO = new UserDAO();
            int flag = 0;
            string pass = usDAO.GetMD5(model.Password1.ToString());
            string username = model.UserName.ToString();
            var query = from Acc in db.AccountSystem
                        where (Acc.UserName == username && Acc.Password1 == pass)
                        select Acc;
            List<AccountSystem> lis = query.ToList();
            foreach (AccountSystem us in lis)
            {
                flag = 1;
                Session["LoaiTaiKhoan"] = us.LoaiTaiKhoan.ToString();
                FormsAuthentication.SetAuthCookie(us.UserName, us.TrangThai);
            }
            if (flag == 1)
            {
                return RedirectToAction("Index", "User");
            }
            else
            {
                ModelState.AddModelError("","Sai tên đăng nhập hoặc mật khẩu");
                return View(model);
            }
        }
        //
        // GET: /Account/LogOn
        public ActionResult LogOn()
        {
            return View();
        }
        public ActionResult Login()
        {
            FormsAuthentication.SignOut();
            return View();
        }
        //
        // POST: /Account/Login

        [HttpPost]
        public ActionResult Login(User model)
        {
            UserDAO usDAO = new UserDAO();
            int flag = 0;
            string pass = usDAO.GetMD5(model.Password1.ToString());
            string username = model.Username.ToString();
            var query = from User in db.Users
                        where (User.Username == username && User.Password1 == pass)
                        select User;
            List<User> danhsach = query.ToList();
            foreach (User us in danhsach)
            {
                flag = 1;
                Session["Name"] = model.Username;
                Session["UserId"] = us.UserID;
                FormsAuthentication.SetAuthCookie(model.Username, model.TinhTrang);
            }
            if (flag == 1)
            {
                return RedirectToAction("Index", "Home");
            }
            else
            {
                ModelState.AddModelError("", "Sai tên đăng nhập hoặc mật khẩu");
                return View(model);
            }
        }

        //
        // POST: /Account/LogOn
        //[HttpPost]
        //public ActionResult LogOn(AdminModel model, string returnUrl)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        if (Membership.ValidateUser(model.UserName, model.Password))
        //        {
        //            FormsAuthentication.SetAuthCookie(model.UserName,);
        //            if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
        //                && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
        //            {
        //                return Redirect(returnUrl);
        //            }
        //            else
        //            {
        //                return RedirectToAction("Index", "Home");
        //            }
        //        }
        //        else
        //        {
        //            ModelState.AddModelError("", "The user name or password provided is incorrect.");
        //        }
        //    }

        //    // If we got this far, something failed, redisplay form
        //    return View(model);
        //}

        //
        // GET: /Account/LogOff dang xuat

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

        //
        // GET: /Account/Register

        public ActionResult Register()
        {
            return View();
        }

        //
        // POST: /Account/Register

        [HttpPost, ValidateInput(false)]
        public ActionResult Register(User model, HttpPostedFileBase file)
        {
            UserDAO usDAO = new UserDAO();
            if (usDAO.ktTrung(model) == true)
            {
                User dk = new User();
                dk.Username = model.Username;
                dk.Password1 = usDAO.GetMD5(model.Password1);
                dk.TenKhachhang = model.TenKhachhang;
                dk.CMND = model.CMND;
                dk.DienThoai = model.DienThoai;
                dk.Email = model.Email;
                dk.DiaChi = model.DiaChi;
                dk.NgayDangKy = DateTime.Now.ToLocalTime();
                if (file != null)
                {
                    if (file.ContentLength > 0)
                    {
                        if ((file.ContentType == "image/jpeg") || (file.ContentType == "image/gif") ||
(file.ContentType == "image/png"))//check allow jpg, gif, png
                        {
                            var fileName = Path.GetFileName(file.FileName);
                            var path = Path.Combine(Server.MapPath("../Images/HinhAnh/"), fileName);
                            file.SaveAs(path);//save image in folder
                            dk.HinhAnh = file.FileName;
                        }
                    }
                }
                dk.CategoriesUserID = 1;
                dk.TinhTrang = true;

                string ngaythang = DateTime.Now.ToLocalTime().ToShortDateString();
                string[] ngaythangs = ngaythang.Split('/');
                string gio = DateTime.Now.ToLocalTime().ToLongTimeString();
                string[] gios = gio.Split(':');
                dk.UserID = "KH";
                foreach (string part in ngaythangs)
                {
                    dk.UserID = dk.UserID + part;
                }
                foreach (string part in gios)
                {
                    dk.UserID = dk.UserID + part;
                }
                string[] ma = dk.UserID.Split(' ');
                dk.UserID = ma[0];

                using (var db = new HandvnContext())
                {
                    db.Users.Add(dk);
                    db.SaveChanges();
                }
                FormsAuthentication.SetAuthCookie(model.Email, false);

                return RedirectToAction("Index", "Home");
            }
            else
            {
                ViewData["key"] = "Tài khoản này đã tồn tại!";
                //ViewBag.CategoriesUserID = new SelectList(db.CategoriesUser, "CategoriesUserID", "TenLoaiNguoiDung", model.CategoriesUserID);
                UserDangKy usdk = new UserDangKy();
                return View(usdk);
            }
        }

        //
        // GET: /Account/ChangePassword

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        //
        // POST: /Account/ChangePassword

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {

                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePasswordSuccess

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
